package com.sxkj.common.pay.wxpay;

import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;

import java.util.Map;

public class WXPay extends com.github.wxpay.sdk.WXPay {

    private WXPayConfig config;

    public WXPay(WXPayConfig config) throws Exception {
        super(config);
        this.config = config;
    }

    public WXPay(final WXPayConfig config, final boolean useSandbox) throws Exception {
        super(config, null, true, useSandbox);
        this.config = config;
    }

    /**
     * @author Zhang Xingliang
     * @description 发红包
     * @date 17:05 2019/12/26
     * @param reqData 向wxpay post的请求数据
     * @return java.util.Map<java.lang.String,java.lang.String>
     * @throws Exception
     **/
    public Map<String, String> sendRedPack(Map<String, String> reqData) throws Exception {
        return this.sendRedPack(reqData, this.config.getHttpConnectTimeoutMs(), this.config.getHttpReadTimeoutMs());
    }

    /**
     * @author Zhang Xingliang
     * @description 发红包
     * @date 17:05 2019/12/26
     * @param reqData 向wxpay post的请求数据
     * @param connectTimeoutMs 连接超时时间，单位是毫秒
     * @param readTimeoutMs 读超时时间，单位是毫秒
     * @return API返回数据
     * @throws Exception
     */
    public Map<String, String> sendRedPack(Map<String, String> reqData, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        String url = WXPayConstants.SEND_REDPACK_URL_SUFFIX;
        String respXml = this.requestWithCert(url, this.fillRebPackRequestData(reqData), connectTimeoutMs, readTimeoutMs);
        return this.processResponseXml(respXml);
    }

    /**
     * 处理 HTTPS API返回数据，转换成Map对象。return_code为SUCCESS时，验证签名。
     *
     * @param xmlStr API返回的XML格式数据
     * @return Map类型数据
     * @throws Exception
     */
    public Map<String, String> processResponseXml(String xmlStr) throws Exception {
        String return_code = "return_code";
        Map<String, String> respData = WXPayUtil.xmlToMap(xmlStr);
        if (respData.containsKey(return_code)) {
            return_code = respData.get(return_code);
        } else {
            throw new Exception(String.format("No `return_code` in XML: %s", xmlStr));
        }

        if (return_code.equals(WXPayConstants.FAIL)) {
            return respData;
        } else if (return_code.equals(WXPayConstants.SUCCESS)) {
            return respData;
        } else {
            throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, xmlStr));
        }
    }
}
